/*
  持久化：
    1：值修改了存储到浏览器
    2：初始值读取浏览器存储
  插件方案(vuex插件)
       vuex-persistedstate
     1:下载安装
     2：store/index.js中导入  import persistedstate from 'vuex-persistedstate'
     3：配制
         plugins:[
           persistedstate({
            paths:['user.token(user模块下的token持久化)','user(整个模块持久化)']
           })
         ]
*/
// import jsCookie from 'js-cookie'
import { sysProfile, sysUser } from '@/api/user'
/* 导入路由 和 路由中暴漏出来的otherRoutes */
import router, { constantRoutes, otherRoutes, resetRouter } from '@/router'
const state = {
  // token: jsCookie.get('token') || ''
  token: '',
  test: '测试',
  userInfo: { username: '游客' }
}
const mutations = {
  SETTOKEN(state, value) {
    state.token = value
    // jsCookie.set('token', value)
  },
  SETTEST(state, value) {
    state.test = value
  },
  // 修改userInfo
  SETUSERINFO(state, value) {
    state.userInfo = value
  },
  // 删除用户信息与token
  LOGOUT(state) {
    state.userInfo = { username: '游客' }
    state.token = ''
    /* 重置路由 */
    resetRouter()
  }
}
// actions返回值加不加async都是promise
const actions = {
  async getUserInfo(ctx) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    // 合并用户信息 Object.assign(目标对象,待合并对象a,待合并对象b...)
    /* 权限访问设置开始 */
    const res3 = Object.assign({}, res.data, res2.data)
    ctx.commit('SETUSERINFO', res3)
    const newArr = otherRoutes.filter(item => {
      if (res3.roles.menus.includes(item.val)) {
        return true
      }
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(newArr)
    router.options.routes = [...constantRoutes, ...newArr] // 让列表显示出来
    console.log('newArr', newArr)
    /* 权限设置结束 */
    // console.log('用户信息', res, res2)
    // console.log(3)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

